//
//  LogInViewController.m
//  ZhiBoYuan
//
//  Created by mac on 2018/4/11.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "LogInViewController.h"
#import "Header.h"
#import "TabVC.h"
//#import "RegistVC.h"

//#import "ForgotVC.h"
#import "JSHAREService.h"

#import "RegisteredViewController.h"

#import "ForgotVCViewController.h"

#import "TeaterRegistViewController.h"

#import "BinDingPhoneViC.h"

#import "XIeYiViewController.h"

@interface LogInViewController ()

@property(nonatomic,strong)NSString *openId;

@property(nonatomic,strong)NSString *type;



@end

@implementation LogInViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    

    
    
    [self layouttUI];
    
   
    
//    [ZYUserManager userInfo].type
//    self.textFildPassword.text = @"qqqqqq";
    
    
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19 * KscreenWidth],NSForegroundColorAttributeName:hui10Color}];
    // 左右按钮颜色
    self.navigationController.navigationBar.tintColor = hui10Color;
    
    
    [JSHAREService cancelAuthWithPlatform:(JSHAREPlatformQQ)];
    
    [JSHAREService cancelAuthWithPlatform:(JSHAREPlatformWechatSession)];
}


-(void)layouttUI {
    
    _imageView = [UIImageView new];
    _imageView.image = [UIImage imageNamed:@"编组"];
    [self.view addSubview:_imageView];
    _imageView.sd_layout
    .topSpaceToView(self.view, NAVIGATION_BAR_HEIGHT+30 * KscreenWidth)
    .centerXIs(self.view.center.x)
    .widthIs(172 * KscreenWidth)
    .heightIs(57 * KscreenHeight);
    
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithActionBlock:^(id  _Nonnull sender) {
        
        _textFildUser.text = @"";
        [Helper delUser];
    }];
    _imageView.userInteractionEnabled = YES;
    
    [_imageView addGestureRecognizer:tap];
    
    
    _textFildUser = [UITextField new];
    _textFildUser.layer.masksToBounds = YES;
    _textFildUser.layer.cornerRadius = 20 * KscreenHeight;
    _textFildUser.layer.borderWidth = 1 * KscreenHeight;
    _textFildUser.layer.borderColor = hui1Color.CGColor;
    _textFildUser.clearButtonMode = UITextFieldViewModeAlways;
    

    
    
    UIView *viewt = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 15 * KscreenWidth, 1 * KscreenHeight)];
    _textFildUser.leftView = viewt;
    
    _textFildUser.leftViewMode = UITextFieldViewModeAlways;
    
    _textFildUser.placeholder = @"请输入账号";
    [self.view addSubview:_textFildUser];
    _textFildUser.sd_layout
    .topSpaceToView(_imageView, 30 * KscreenHeight)
    .rightSpaceToView(self.view,50 * KscreenWidth)
    .leftSpaceToView(self.view,50 * KscreenWidth)
    .heightIs(40 * KscreenHeight);
    
    
    
    _textFildPassword = [UITextField new];
    _textFildPassword.layer.masksToBounds = YES;
    _textFildPassword.layer.cornerRadius = 20 * KscreenHeight;
    _textFildPassword.layer.borderWidth = 1 * KscreenWidth;
    _textFildPassword.layer.borderColor = hui1Color.CGColor;
    _textFildPassword.secureTextEntry = YES;
    _textFildPassword.placeholder = @"请输入密码";
    _textFildPassword.clearButtonMode = UITextFieldViewModeAlways;
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 15 * KscreenWidth, 1 * KscreenHeight)];
    _textFildPassword.leftView = view;
    
    _textFildPassword.leftViewMode = UITextFieldViewModeAlways;
    [self.view addSubview:_textFildPassword];
    _textFildPassword.sd_layout
    .topSpaceToView(_textFildUser, 10 * KscreenHeight)
    .rightSpaceToView(self.view,50 * KscreenWidth)
    .leftSpaceToView(self.view,50 * KscreenWidth)
    .heightIs(40 * KscreenHeight);
    
    
    _forgetButton = [UIButton new];
    BTN_MSG_FUNC(_forgetButton,forgetSender:);
    [_forgetButton setTitle:@"忘记密码？" forState:(UIControlStateNormal)];
    [_forgetButton setBackgroundColor:[UIColor whiteColor]];
    [_forgetButton setTitleColor:hui5Color forState:UIControlStateNormal];
    
    _forgetButton.titleLabel.font= [UIFont systemFontOfSize:14 * KscreenWidth];
    
    [self.view addSubview:_forgetButton];
    _forgetButton.sd_layout
    .topSpaceToView(_textFildPassword,10 * KscreenHeight)
    .rightSpaceToView(self.view,50 * KscreenWidth)
    .widthIs(80 * KscreenWidth)
    .heightIs(30 * KscreenHeight);
    
    
    _loginButton = [UIButton new];
    _loginButton.layer.masksToBounds = YES;
    _loginButton.layer.cornerRadius = 20 * KscreenHeight;
    BTN_MSG_FUNC(_loginButton,loginSender:);
    [_loginButton setTitle:@"登 录" forState:(UIControlStateNormal)];
    [_loginButton setBackgroundColor:ZhuTiColor];
    
     [self.view addSubview:_loginButton];
    _loginButton.sd_layout
    .topSpaceToView(_forgetButton,10 * KscreenHeight)
    .rightSpaceToView(self.view, 50 * KscreenWidth)
    .leftSpaceToView(self.view, 50 * KscreenWidth)
    .heightIs(40 * KscreenHeight);
    
    
    _registButton = [UIButton new];
    _registButton.layer.masksToBounds = YES;
    _registButton.layer.cornerRadius = 20 * KscreenWidth;
    
    _registButton.layer.masksToBounds = YES;
    _registButton.layer.cornerRadius = 20 *KscreenHeight;
    _registButton.layer.borderWidth = 1 * KscreenWidth;
    _registButton.layer.borderColor = ZhuTiColor.CGColor;
    [_registButton setTitle:@"注 册" forState:(UIControlStateNormal)];
    [_registButton setBackgroundColor:[UIColor whiteColor]];
    BTN_MSG_FUNC(_registButton,registSender:);
    
    [_registButton setTitleColor:ZhuTiColor forState:UIControlStateNormal];
    
    [self.view addSubview:_registButton];
    _registButton.sd_layout
    .topSpaceToView(_loginButton,10 * KscreenHeight)
    .rightSpaceToView(self.view, 50 * KscreenWidth)
    .leftSpaceToView(self.view, 50 * KscreenWidth)
    .heightIs(40 * KscreenHeight);
    
    
    
    _linelabel = [UILabel new];
    
    _linelabel.backgroundColor = [UIColor whiteColor];
    
    _linelabel.text = @"–––––––––––––––– 第三方登录 ––––––––––––––––";
    _linelabel.font = [UIFont systemFontOfSize:14 * KscreenWidth];
    
    [_linelabel setTextAlignment:(NSTextAlignmentCenter)];
    _linelabel.textColor = hui3Color;
    
    [self.view addSubview:_linelabel];
    
    _linelabel.sd_layout
    .topSpaceToView(_registButton,20 * KscreenHeight)
    .rightSpaceToView(self.view, 0)
    .leftSpaceToView(self.view, 0)
    .heightIs(30 * KscreenHeight);
    
    
    _wechatButton = [UIButton new];
    _wechatButton.layer.masksToBounds = YES;
    _wechatButton.layer.cornerRadius = 20 * KscreenHeight;
    
    _wechatButton.layer.masksToBounds = YES;
//    [_wechatButton setTitle:@"微信" forState:(UIControlStateNormal)];
    [_wechatButton setBackgroundColor:[UIColor whiteColor]];
    BTN_MSG_FUNC(_wechatButton,wxSender:);
    
    [_wechatButton setBackgroundImage:[UIImage imageNamed:@"微信-3"] forState:(UIControlStateNormal)];
    
    [_wechatButton setTitleColor:ZhuTiColor forState:UIControlStateNormal];
    
    [self.view addSubview:_wechatButton];
    _wechatButton.sd_layout
    .topSpaceToView(_linelabel,10 * KscreenHeight)
    .rightSpaceToView(self.view, 90 * KscreenWidth)
    .widthIs(50 * KscreenWidth)
    .heightIs(50 * KscreenHeight);

 
    _qqButton = [UIButton new];
    _qqButton.layer.masksToBounds = YES;
    _qqButton.layer.cornerRadius = 20 * KscreenHeight;
    
    _qqButton.layer.masksToBounds = YES;
    _qqButton.layer.cornerRadius = 20 * KscreenWidth;
//    _qqButton.layer.borderWidth = 1;
//    _qqButton.layer.borderColor = ZhuTiColor.CGColor;
//    [_qqButton setTitle:@"qq" forState:(UIControlStateNormal)];
    [_qqButton setBackgroundColor:[UIColor whiteColor]];
    
    [_qqButton setBackgroundImage:[UIImage imageNamed:@"QQ-3"] forState:(UIControlStateNormal)];
    
    
    BTN_MSG_FUNC(_qqButton,qqSender:);
    
    [_qqButton setTitleColor:ZhuTiColor forState:UIControlStateNormal];
    
    [self.view addSubview:_qqButton];
    _qqButton.sd_layout
    .topSpaceToView(_linelabel,10 * KscreenHeight)
    .leftSpaceToView(self.view,90 * KscreenWidth)
    .widthIs(50 * KscreenWidth)
    .heightIs(50 * KscreenHeight);
    
    
    _selectedBtn = [UIButton new];
    [_selectedBtn setBackgroundColor:[UIColor whiteColor]];
//    [_selectedBtn setBackgroundImage:[UIImage imageNamed:@"选择"] forState:(UIControlStateNormal)];
    [_selectedBtn setBackgroundImage:[UIImage imageNamed:@"未选择"] forState:UIControlStateSelected];
    [_selectedBtn setBackgroundImage:[UIImage imageNamed:@"选择"] forState:0];
    BTN_MSG_FUNC(_selectedBtn,xieyiAction);
    [_selectedBtn setTitleColor:ZhuTiColor forState:UIControlStateNormal];
    [self.view addSubview:_selectedBtn];
    
    _selectedBtn.sd_layout
    .bottomSpaceToView(self.view, 60 * KscreenHeight)
//    .rightSpaceToView(self.view, 0)
    .leftSpaceToView(self.view, 50 * KscreenWidth)
    .widthIs(20 * KscreenWidth)
    .heightIs(20 * KscreenHeight);
    

    _xieyiLable = [UILabel new];
    _xieyiLable.text = @"已阅读并同意";
    _xieyiLable.textAlignment = NSTextAlignmentRight;
    _xieyiLable.font = [UIFont systemFontOfSize:14 * KscreenWidth];
    [_xieyiLable setTextAlignment:(NSTextAlignmentCenter)];
    _xieyiLable.textColor = hui3Color;
    [self.view addSubview:_xieyiLable];
    
    _xieyiLable.sd_layout
    .bottomSpaceToView(self.view, 60 * KscreenHeight)
    .leftSpaceToView(_selectedBtn, 0)
    .widthIs(100 * KscreenWidth)
    .heightIs(20 * KscreenHeight);
    
    
    _xieyiBtn = [UIButton new];
    [_xieyiBtn setTitle:@"《用户协议》" forState:0];
    _xieyiBtn.font = [UIFont systemFontOfSize:14 * KscreenWidth];
    [_xieyiBtn setTitleColor:[UIColor redColor] forState:0];
    BTN_MSG_FUNC(_xieyiBtn,ChaKanXieYi);
    [self.view addSubview:_xieyiBtn];
    
    _xieyiBtn.sd_layout
    .bottomSpaceToView(self.view, 60 * KscreenHeight)
    .leftSpaceToView(_selectedBtn, 80 * KscreenWidth)
    .widthIs(100 * KscreenWidth)
    .heightIs(20 * KscreenHeight);
    
    
    _laastLabel = [UILabel new];
    
    _laastLabel.backgroundColor = [UIColor whiteColor];
    
    _laastLabel.text = @"——— Copy right © 2010-2017 Zby du.cn All Right Reserved ———";
    _laastLabel.font = [UIFont systemFontOfSize:10 * KscreenWidth];
    
    [_laastLabel setTextAlignment:(NSTextAlignmentCenter)];
    _laastLabel.textColor = hui3Color;
    
    [self.view addSubview:_laastLabel];
    
    _laastLabel.sd_layout
    .bottomSpaceToView(self.view, 10 * KscreenHeight)
    .rightSpaceToView(self.view, 0)
    .leftSpaceToView(self.view, 0)
    .heightIs(30 * KscreenHeight);
    
    
    _textFildUser.text  =  [Helper redUser];
   
    

//     self.textFildUser.text = [ZYUserManager userInfo].phone;
    

    
}

//协议勾选事件
-(void)xieyiAction{
    _selectedBtn.selected = !_selectedBtn.selected;
}

//点击进入查看协议
-(void)ChaKanXieYi{
    
    XIeYiViewController *xieyiVC = [[XIeYiViewController alloc]init];
    xieyiVC.isComeFromLogin = YES;
    [self.navigationController pushViewController:xieyiVC animated:YES];
    
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [_textFildUser resignFirstResponder];
    [_textFildPassword resignFirstResponder];
}

#pragma mark ----------------------- 登录 ------------------------
-(void)loginSender:(UIButton *)sender{
    
    if (_textFildUser.text.length != 11) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"请输入正确的手机号" message:@"" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil, nil];
        [alertView show];
        return;
    }
    
    if (_textFildPassword.text.length == 0) {
        [MBProgressHUD showTextOnly:self.view message:@"请输入密码" delay:2.0];
        return;
    }
    
    if (_selectedBtn.selected) {
        [MBProgressHUD showTextOnly:self.view message:@"请先阅读用户协议" delay:2.0];
        return;
    }
    
    [self.view endEditing:YES];
    SGParameter *parameter  = [[SGParameter alloc] init];
    parameter.body = @{@"phone":_textFildUser.text,
                       @"password":_textFildPassword.text
                       };
     __weak __typeof(&*self)weakSelf = self;
    [SGHttpTool POST:[NSString stringWithFormat:@"%@g=Client&m=Login&a=login",HTTPP] parameter:parameter sucess:^(id responseObject) {
        NSLog(@"%@",responseObject);
        
        NSDictionary *dic = responseObject;
        
        [weakSelf enterMainPage:dic third:NO];

    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
  
}


- (void)registSender:(UIButton *)sender {
    RegisteredViewController * vc = [[RegisteredViewController alloc]initWithNibName:@"RegisteredViewController" bundle:nil];
    
    [self.navigationController pushViewController:vc animated:YES];
}


- (void)forgetSender:(UIButton *)sender {
    NSLog(@"忘记密码");
    

    ForgotVCViewController * vc = [[ForgotVCViewController alloc]initWithNibName:@"ForgotVCViewController" bundle:nil];

    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark ----------------------- 微信 ------------------------
-(void)wxSender:(UIButton *)sender{
     NSLog(@"微信登录");
    [JSHAREService getSocialUserInfo:JSHAREPlatformWechatSession handler:^(JSHARESocialUserInfo *userInfo, NSError *error) {
        NSString *alertMessage;
        NSString *title;
        if (error) {
            title = @"失败";
            alertMessage = @"无法获取到用户信息";
        }else{
            title = userInfo.name;
            NSString *gender = nil;
            if (userInfo.gender == 1) {
                gender = @"男";
            }else if (userInfo.gender == 2){
                gender = @"女";
            }else{
                gender = @"未知";
            }
            
            alertMessage = [NSString stringWithFormat:@"昵称: %@\n 头像链接: %@\n 性别: %@\n",userInfo.name,userInfo.iconurl,gender];
            
            
            if (userInfo.openid.length > 0) {
                _type =[NSString string];
                _type = @"2";
                
                [self logtinThirdFromPlatform:JSHAREPlatformWechatSession openid:userInfo.openid phone:@"" type:_type];
            }else{
                [MBProgressHUD showTextOnly:self.view message:@"系统异常" delay:2.0f];
            }
        }
//        UIAlertView *Alert = [[UIAlertView alloc] initWithTitle:title message:alertMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [Alert show];
//        });
     
    }];
}

#pragma mark ----------------------- QQ ------------------------
-(void)qqSender:(UIButton *)sender{
    NSLog(@"qq登录");
    
//    NSString *openid = @"12313132131313"; ///已经绑定
//
//    openid = @"12313132131232323313";
//
//
//     [self logtinThirdFromPlatform:JSHAREPlatformQQ openid:openid phone:@""];
//    return;
    
    
    [JSHAREService getSocialUserInfo:JSHAREPlatformQQ handler:^(JSHARESocialUserInfo *userInfo, NSError *error) {
        NSString *alertMessage;
        NSString *title;
        if (error) {
            title = @"失败";
            alertMessage = @"无法获取到用户信息";
        }else{
            title = userInfo.name;
            NSString *gender = nil;
            if (userInfo.gender == 1) {
                gender = @"男";
            }else if (userInfo.gender == 2){
                gender = @"女";
            }else{
                gender = @"未知";
            }
            
            alertMessage = [NSString stringWithFormat:@"昵称: %@\n 头像链接: %@\n 性别: %@\n%@",userInfo.name,userInfo.iconurl,gender,userInfo.userOriginalResponse];
            
            if (userInfo.openid.length > 0) {
                
                _type =[NSString string];
                _type = @"1";
                
                [self logtinThirdFromPlatform:JSHAREPlatformQQ openid:userInfo.openid phone:@"" type:_type];
            }else{
                [MBProgressHUD showTextOnly:self.view message:@"系统异常" delay:2.0f];
            }
            
          
        }
//        UIAlertView *Alert = [[UIAlertView alloc] initWithTitle:title message:alertMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [Alert show];
//        });
        
    }];
    
}

#pragma mark ----------------------- 3 login  ------------------------
- (void)logtinThirdFromPlatform:(JSHAREPlatform)platform openid:(NSString *)openid phone:(NSString *)phone type:(NSString *)type{
    
    
    _openId = [NSString string];
    _openId = openid;
    
    
    if (platform == JSHAREPlatformQQ) {
        SGParameter *parameter  = [[SGParameter alloc] init];
        
        NSString *NewOpenid = [NSString stringWithFormat:@"%@1",openid];
        
        parameter.body  = @{
                            @"openid":NewOpenid,
                            @"type":type,
                            @"phone":phone
                            };
        
        NSString *lastUrl  =  @"g=Client&m=Login&a=oauths";
        NSString *url      = [NSString stringWithFormat:@"%@%@",HTTPP,lastUrl] ;
         __weak __typeof(&*self)weakSelf = self;
        [SGHttpTool POST:url parameter:parameter sucess:^(id responseObject) {
            
            NSDictionary *dic = responseObject;
            
            NSLog(@"登录结果 %@",dic);
            [weakSelf enterMainPage:dic third:YES];
            
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
            
        }];
        
    }else{
        SGParameter *parameter  = [[SGParameter alloc] init];
        
        NSString *NewOpenid = [NSString stringWithFormat:@"%@1",openid];
        
        parameter.body  = @{
                            @"openid":NewOpenid,
                            @"type":type,
                            @"phone":phone
                            };
        
        NSString *lastUrl  =  @"g=Client&m=Login&a=oauths";
        NSString *url      = [NSString stringWithFormat:@"%@%@",HTTPP,lastUrl] ;
        __weak __typeof(&*self)weakSelf = self;
        [SGHttpTool POST:url parameter:parameter sucess:^(id responseObject) {
            
            NSDictionary *dic = responseObject;
            
            NSLog(@"登录结果 %@",dic);
            [weakSelf enterMainPage:dic third:YES];
            
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
            
        }];
        
    }
    
}

#pragma mark ----------------------- 进入主页 ------------------------
-(void)enterMainPage:(NSDictionary *)dic third:(BOOL)third{
    
    if ([dic[@"status"] intValue] == 200) {
        [MBProgressHUD showTextOnly:self.view message:@"登录成功" delay:3.0f];
        
        UserinfoModel *model = [UserinfoModel mj_objectWithKeyValues:dic[@"data"][@"user_info"]];
        model.isLogIn = @"loginIn";
        [ZYUserManager saveUserInfo:model];
        NSLog(@"%@",[ZYUserManager userInfo].small_img);
        
        if ([[ZYUserManager userInfo].type integerValue] == 2 ) {
            ((AppDelegate *)[UIApplication sharedApplication].delegate).teacher = YES;
        }else{
            ((AppDelegate *)[UIApplication sharedApplication].delegate).teacher = NO;
        }
        
        [_textFildPassword resignFirstResponder];
        
        TabVC * vc = [[TabVC alloc]init];
        self.view.window.rootViewController = vc;
        
        [Helper userSave: _textFildUser.text];
        
        
     // + (BOOL)cancelAuthWithPlatform:(JSHAREPlatform)platfrom;
        

        
        
        
        
    }else if ([dic[@"status"] intValue] == 202){
        UserinfoModel *model = [ZYUserManager userInfo];
        
        model = [UserinfoModel mj_objectWithKeyValues:dic[@"data"][@"user_info"]];
        [ZYUserManager saveUserInfo:model];
        //            [MBProgressHUD showTextOnly:self.view message:dic[@"msg"] delay:2.0f];
        
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:dic[@"msg"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil, nil];
        [alertView show];
        
        TeaterRegistViewController *teacherRVC = [[TeaterRegistViewController alloc]init];
        [self.navigationController pushViewController:teacherRVC animated:YES];
        
    }else if ([dic[@"status"] intValue] == 203){
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"认证审核中，请耐心等待，审核通过后方可登陆" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil, nil];
        [alertView show];
        
    }else if ([dic[@"status"] intValue] == 501){
        
        if (third)
        {
            NSLog(@"绑定手机📱📱");
            BinDingPhoneViC *vc = [[BinDingPhoneViC alloc]init];
            
            vc.openid = _openId;
            vc.type = _type;
            
            vc.binding = ^(BOOL zhuce) {
                
                
                if (zhuce) {
                    [self registSender:nil];
                }
                
            };
            
            [self.navigationController pushViewController:vc animated:YES];
            
        }else{
            [MBProgressHUD showTextOnly:self.view message:dic[@"msg"] delay:2.0f];
        }
        

        
        
        
    }else{
         [MBProgressHUD showTextOnly:self.view message:dic[@"msg"] delay:2.0f];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
